package com.example.wordmemory;

import android.content.Intent;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.wordmemory.utils.WordDBHelper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;

public class MainActivity extends AppCompatActivity {
    private WordDBHelper dbHelper;
    private TextView tvDate;
    private CardView cardSignIn, cardLearn, cardReview;
    private LinearLayout navWordManagement, navLearningProgress, navReserved;
    private boolean isSignedToday = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        dbHelper = new WordDBHelper(this);
        tvDate = findViewById(R.id.tv_date);
        cardSignIn = findViewById(R.id.card_signin);
        cardLearn = findViewById(R.id.card_learn);
        cardReview = findViewById(R.id.card_review);
        navWordManagement = findViewById(R.id.nav_word_management);
        navLearningProgress = findViewById(R.id.nav_learning_progress);
        navReserved = findViewById(R.id.nav_reserved);

        // 1. 设置日期
        String today = new SimpleDateFormat("MM/dd EEE.", Locale.getDefault()).format(new Date());
        tvDate.setText(today);


        // 2. 检查今天是否已签到，已签到则禁用卡片点击
        String todayDb = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        isSignedToday = dbHelper.isSigned(todayDb);
        cardSignIn.setAlpha(isSignedToday ? 0.5f : 1f);
        cardSignIn.setClickable(!isSignedToday);
        TextView tvSignIn = findViewById(R.id.tv_signin);
        if (isSignedToday) {
            tvSignIn.setText("已签到");
        } else {
            tvSignIn.setText("签到");
        }

        // 3. 签到卡片点击事件
        cardSignIn.setOnClickListener(v -> {
            if (isSignedToday) return;
            long res = dbHelper.insertSignIn(todayDb);
            if (res != -1) {
                Toast.makeText(this, "签到成功", Toast.LENGTH_SHORT).show();
                cardSignIn.setAlpha(0.5f);
                cardSignIn.setClickable(false);
                tvSignIn.setText("已签到");
                isSignedToday = true;
            } else {
                Toast.makeText(this, "签到失败", Toast.LENGTH_SHORT).show();
            }
        });

        // 4. 学习卡片点击跳转
        cardLearn.setOnClickListener(v -> {
            Intent intent = new Intent(this, WordLearning.class);
            startActivity(intent);
        });
        // 5. 复习卡片点击跳转
        cardReview.setOnClickListener(v -> {
            Intent intent = new Intent(this, WordLearning.class);
            intent.putExtra("mode", "review");
            startActivity(intent);
        });

        // 6. 底部导航栏跳转
        navWordManagement.setOnClickListener(v -> {
            Intent intent = new Intent(this, WordManagement.class);
            startActivity(intent);
        });
        navLearningProgress.setOnClickListener(v -> {
            Intent intent = new Intent(this, LearningProgress.class);
            startActivity(intent);
        });
        navReserved.setOnClickListener(v -> {
            // 预留页面，可根据需求跳转

//            测试4、根据遗忘曲线推送复习任务（BroadcastReceiver：接收系统时间变化触发复习提醒）
//            Intent intent = new Intent(this, ReviewReminderReceiver.class);
//            sendBroadcast(intent);

            Intent intent = new Intent("com.example.wordmemory.TEST_REVIEW_REMINDER");
            intent.setClass(this, ReviewReminderReceiver.class);
            sendBroadcast(intent);
//            Toast.makeText(this, "功能开发中", Toast.LENGTH_SHORT).show();
        });

        // 设置每天定时复习提醒
        setDailyReviewAlarm();

        // 主页面统计
        TextView tvLearnProgress = findViewById(R.id.tv_learn_progress);
        TextView tvReviewCount = findViewById(R.id.tv_review_count);
        tvLearnProgress.setText(dbHelper.getStudyCount() + "/" + dbHelper.getWordsCount());
        tvReviewCount.setText(String.valueOf(dbHelper.getTodayReviewWords().size()));
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 刷新学习进度和今日应复习单词数
        TextView tvLearnProgress = findViewById(R.id.tv_learn_progress);
        TextView tvReviewCount = findViewById(R.id.tv_review_count);
        if (tvLearnProgress != null && tvReviewCount != null && dbHelper != null) {
            tvLearnProgress.setText(dbHelper.getStudyCount() + "/" + dbHelper.getWordsCount());
            tvReviewCount.setText(String.valueOf(dbHelper.getTodayReviewWords().size()));
        }
    }

    // 每天定时批量复习提醒
    private void setDailyReviewAlarm() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, ReviewReminderReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.set(java.util.Calendar.HOUR_OF_DAY, 8);
        calendar.set(java.util.Calendar.MINUTE, 0);
        calendar.set(java.util.Calendar.SECOND, 0);
        long triggerAtMillis = calendar.getTimeInMillis();
        if (System.currentTimeMillis() > triggerAtMillis) {
            triggerAtMillis += 24 * 60 * 60 * 1000;
        }
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, AlarmManager.INTERVAL_DAY, pendingIntent);
    }

    @Override
    protected void onDestroy() {
        dbHelper.close();
        super.onDestroy();
    }
}